const router = require('koa-router')();
const cc = require('../conCtl');
const js = require('../jsCtl');
const db = require('../dbCtl');

/**
@hostpath = http://127.0.0.1/client/address
 */

/** 查询用户列表
###
    GET {{hostpath}}?openid=oM2uY5_2SnQhKEwbHMKI-Bwcampg
### */
router.get('/', async c => {
  js.check_params(
    !c.query.openid && '!用户ID');

  let data = await db.model('t_user_address').where('state=1&&openid=?', c.query.openid).select();

  cc.send(c, data);
});


/** 更新用户地址
###
    POST {{hostpath}}
    Content-Type: application/json

    {
        "address_id":1,
        "openid":"oM2uY5_2SnQhKEwbHMKI-Bwcampg",
        "phone":"13023663737",
        "name":"向国亮",
        "is_default":"1",
        "province":"四川省",
        "city":"成都市",
        "area":"武侯区",
        "address":"环球中心"
    }
### */
router.post('/', async c => {
  js.check_params(!c.request.body.openid && '!用户openid')
  js.check_params(!c.request.body.phone && '?电话号码')
  js.check_params(!c.request.body.name && '?姓名')
  js.check_params(!c.request.body.name && '?省')
  js.check_params(!c.request.body.name && '?市')
  js.check_params(!c.request.body.name && '?区/县')
  js.check_params(!c.request.body.name && '?详细地址')

  let data = c.request.body;
  if (!c.request.body.address_id) {
    delete data.address_id;
  }
  //判断当前新增或修改的数据为默认值
  if (data.is_default == 1)
    //将当前用户的所有地址数据默认值改为否
    await db.model('t_user_address').where('state=1&&openid=?', data.openid).update({ is_default: 0 });


  await db.model('t_user_address').insertOrUpdate(data);

  cc.send(c);
});

/** 修改用户地址默认值
###
    POST {{hostpath}}/default
    Content-Type: application/json

    {
        "address_id":23,
        "openid":"oM2uY5_2SnQhKEwbHMKI-Bwcampg",
        "is_default":"1"
    }
### */
router.post('/default', async c => {
  js.check_params(!c.request.body.openid && '!用户openid')

  let data = c.request.body;
  
  //判断当前修改的数据为默认值为是时
  if (data.is_default == 1)
    //将当前用户的所有地址数据默认值改为否
    await db.model('t_user_address').where('state=1&&openid=?', data.openid).update({ is_default: 0 });


  await db.model('t_user_address').where('address_id=?',data.address_id).update({is_default:data.is_default});

  cc.send(c);
});

/** 删除用户地址
###
    DELETE {{hostpath}}/3
### */
router.del('/:id', async c => {

  let data = c.params;

  await db.model('t_user_address').where('address_id=?', data.id).relyUpdate('删除失败', {
    state: 0
  });

  cc.send(c);
});

module.exports = router;